package com.zhongen.dingtalk;

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 获取钉钉登录 access_token 存放在redis中 失效后重新获取新的 并重新存放
 */
@Component
@RequiredArgsConstructor
public class GetDingDingLoginToken {

	@Resource
	private RedisTemplate<String, Object> redisTemplate;

	public String getToken() {
		String accessToken = "";
		// 从 redis判断是否有token 获取后有效时间2小时
		if (redisTemplate.hasKey("access_token")) {
			// 判断失效时间 存活时间小于 10分钟重新获取
			long accessTokenExpire = redisTemplate.getExpire("access_token");
			if (accessTokenExpire < 1) {
				return newOneInRedis();
			}
			accessToken = redisTemplate.opsForValue().get("access_token").toString();
			return accessToken;
		}
		// 没有 获取新的 重新存放到redis 并返回 相应的 token
		return newOneInRedis();
	}

	/**
	 * 获取新的token 并存入redis 中
	 * @return
	 */
	private String newOneInRedis() {
		String accessToken;
		// 移除对应key
		redisTemplate.delete("access_token");
		// 重新获取
		accessToken = getNewToken();
		// redis 存储 新的token 并设置存活时间
		redisTemplate.opsForValue().set("access_token", accessToken, 7200);
		// 返回新的token
		return accessToken;
	}

	/**
	 * 获取钉钉 access_token
	 */
	private String getNewToken() {
		try {
			com.aliyun.dingtalkoauth2_1_0.Client client = GetDingDingLoginToken.createClient();
			com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
				.setAppKey("dinghagbwymy1kwwdhwp")
				.setAppSecret("3P4iBcbHraJGbRrewDmUGLjE9IAKza_VxOUAH00R9qJllER4x0vDY0t2LdUTh8a9");
			// 测试用账号
			// .setAppKey("dingxu8kbmfvatkzknbv")
			// .setAppSecret("YG5IedpJ_rUqMbveifKDE4Soy_pAc92JHoGMyPfxK83HdGTwiUlIvkM2its9BK8C");
			GetAccessTokenResponse accessToken = client.getAccessToken(getAccessTokenRequest);
			return accessToken.getBody().accessToken;
		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 使用 Token 初始化账号Client
	 * @return Client
	 * @throws Exception /
	 */
	public static com.aliyun.dingtalkoauth2_1_0.Client createClient() throws Exception {
		com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
		config.protocol = "https";
		config.regionId = "central";
		return new com.aliyun.dingtalkoauth2_1_0.Client(config);
	}

}
